package com.sixdog.regulate.scheduled;

import com.sixdog.regulate.adapter.ActionAdapter;
import com.sixdog.regulate.bean.Action;
import com.sixdog.regulate.bean.Task;
import com.sixdog.regulate.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.*;

//action定时任务类，初始化时以静态的方式拿到任务列表staticTasks
@Configuration
@EnableScheduling
public class EctActionScheduled implements SchedulingConfigurer{

    @Autowired
    private ActionAdapter actionAdapter;


    private static List<Task> staticTasks;

    public static List<Task> getStaticTask() {
        return staticTasks;
    }
    public static void setStaticTask(List<Task> staticTask) {
        EctActionScheduled.staticTasks = staticTask;
    }



    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//        System.out.println(Arrays.toString(staticTasks.toArray()) + "configureTasks");
        staticTasks.forEach(task -> {
            if (task.isEnable()){
                //任务执行线程
                Runnable runnable = () -> {
                    //不放在线程中的话，会按顺序来执行。
                    task.getActions().forEach(action -> {
                        new Thread(() -> {
                            // TODO：在此处编写逻辑代码......
                            actionAdapter.executeAction(action);
//                          System.out.println(Thread.currentThread().getName());
                        }).start();
                    });
                };
                //任务触发器
                Trigger trigger = triggerContext -> {
                    //获取定时触发器，这里可以每次从数据库获取最新记录，更新触发器，实现定时间隔的动态调整
                    CronTrigger cronTrigger = new CronTrigger(task.getCron());    //0 0/1 * * * ? 每一分钟执行一次
                    return cronTrigger.nextExecutionTime(triggerContext);
                };
                //注册任务
                taskRegistrar.addTriggerTask(runnable, trigger);
            }
        });
    }

}
